<script setup>
import {
  listUser,
  getUserInfo,
  updateUser,
  addUser,
  delUser,
  resetPwd,
  changeUserState,
  listDept,
} from "@/api/hospital";
const { proxy } = getCurrentInstance();
const { sys_user_sex, sys_normal_disable, sys_role } = proxy.useDict(
  "sys_user_sex",
  "sys_normal_disable",
  "sys_role"
);
const loading = ref(true);
const list = ref([]);
const deptList = ref([]);
const total = ref(0);
const open = ref(false);
const title = ref("");
// 查询参数
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    name: undefined,
    dept: undefined,
  },
  rules: {
    username: [
      { required: true, message: "登录名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "登录名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickname: [
      { required: true, message: "姓名不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "姓名长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    gender: [
      {
        required: true,
        message: "必须指定性别",
        trigger: "blur",
      },
    ],
    dept_id: [
      {
        required: true,
        message: "必须指定科室",
        trigger: "blur",
      },
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        min: 1,
        max: 20,
        message: "手机号长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    role: [
      {
        required: true,
        message: "必须指定角色",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.data;
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.dept = undefined;
  queryParams.value.name = undefined;
  handleQuery();
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: undefined,
    username: undefined,
    nickname: undefined,
    password: undefined,
    gender: undefined,
    phone: undefined,
    dept_id: undefined,
    role: undefined,
  };
  proxy.resetForm("userRef");
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.id;
  getUserInfo(userId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户信息";
  });
}

/** 状态切换 */
function handleStatusChange(row) {
  let text = row.state === "1" ? "启用" : "停用";
  proxy.$modal
    .confirm("确认要" + text + '姓名为"' + row.nickname + '"的用户吗?')
    .then(function () {
      return changeUserState(row.id, row.state);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.state = row.state === "0" ? "1" : "0";
    });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateUser(form.value).then((response) => {
          if (response.code == 200) proxy.$modal.msgSuccess("修改用户信息成功");
          else proxy.$modal.alertError(response.msg);
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          if (response.code == 200) proxy.$modal.msgSuccess("新增用户成功");
          else proxy.$modal.alertError(response.msg);
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const uNames = row.nickname || names.value;
  const uIds = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除姓名为"' + uNames + '"的数据项？')
    .then(function () {
      return delUser(uIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleResetPwd(row) {
  resetPwd(row.id).then((response) => {
    if (response.code == 200) proxy.$modal.msgSuccess("重置成功,默认密码为123");
    else proxy.$modal.alertError(response.msg);
  });
}

/** 获取部门列表 */
function getDeptList() {
  listDept().then((res) => {
    deptList.value = res.data;
  });
}

getDeptList();
getList();
</script>

<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          style="width: 150px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="queryParams.dept"
          placeholder="请输入部门名称"
          clearable
          style="width: 150px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column
        label="登录账号"
        align="center"
        key="username"
        prop="username"
      />
      <el-table-column
        label="姓名"
        align="center"
        key="nickname"
        prop="nickname"
      />
      <el-table-column
        label="部门"
        align="center"
        key="department"
        prop="department"
      />
      <el-table-column
        label="性别"
        align="center"
        key="genderStr"
        prop="genderStr"
      />
      <el-table-column
        label="手机号码"
        align="center"
        key="phone"
        prop="phone"
      />
      <el-table-column
        label="角色"
        align="center"
        key="roleStr"
        prop="roleStr"
      />
      <el-table-column label="状态" align="center" key="state">
        <template #default="scope">
          <el-switch
            v-model="scope.row.state"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="重置密码" placement="top">
            <el-button
              link
              type="primary"
              icon="Key"
              @click="handleResetPwd(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录名称" prop="username">
              <el-input
                v-model="form.username"
                placeholder="登录名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickname">
              <el-input
                v-model="form.nickname"
                placeholder="请输入姓名"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select filterable v-model="form.gender" placeholder="请选择">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="dept_id">
              <el-select filterable v-model="form.dept_id" placeholder="请选择">
                <el-option
                  v-for="dict in deptList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select filterable v-model="form.role" placeholder="请选择">
                <el-option
                  v-for="dict in sys_role"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped></style>
